package com.zeng.user.web.listener;

import com.zeng.configuration.microprofile.config.DefaultConfigProviderResolver;
import com.zeng.user.domain.User;
import com.zeng.user.management.UserManager;
import com.zeng.user.service.UserService;
import com.zeng.context.ComponentContext;
import org.eclipse.microprofile.config.Config;
import org.eclipse.microprofile.config.spi.ConfigProviderResolver;

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.lang.management.ManagementFactory;

/**
 * @author zyb
 * @date 2021-03-07 10:33
 */
@Deprecated
public class TestInitializerListener implements ServletContextListener {
    private ServletContext servletContext;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        servletContext = servletContextEvent.getServletContext();
        registerUserTest();
        registerUserMBean();
        configTest();

    }

    private void configTest() {
        ConfigProviderResolver providerResolver = DefaultConfigProviderResolver.instance();
        Config config = providerResolver.getConfig(Thread.currentThread().getContextClassLoader());
        String value = config.getValue("application.name", String.class);
        System.out.println("application.name = " + value);
    }

    private void registerUserMBean() {
        MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
        try {
            ObjectName objectName = new ObjectName("com.zeng.user.management:type=user");
            User user = new User();
            user.setPhoneNumber("123456");
            mBeanServer.registerMBean(new UserManager(user), objectName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void registerUserTest() {
        UserService userService = ComponentContext.lookup("bean/UserService");
        User user = new User();
        user.setEmail("test@qq.com");
        user.setPassword("1212312");
        user.setPhoneNumber("18212313213");
        userService.register(user);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

}
